import { Button, Input, Popconfirm, Radio, Select, Table } from 'antd'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { commonInputProps, commonSelectProps } from '@/views/ShoppingCart/commonProps.ts'
import { copyOrdersToCart, deleteDraftOrder, getOrderList, pauseTheOrder } from '@/api/shoppingCart.ts'
import { getItem, hsHandleTableDateTime, initPageType, message, PERMISSIONS, usePageChange } from '@hs-admin/utils'
import { getAllProjectOptions } from '@/api/common.ts'
import { useNavigate } from 'react-router-dom'
import { clearLocalShopping } from '@/views/ShoppingCart/LocalShoppingData.ts'

const stateOptions = [
  {
    label: '全部',
    value: ''
  },
  {
    label: '处理中',
    value: 'processing'
  },
  {
    label: '部分生效',
    value: 'part_effected'
  },
  {
    label: '已生效',
    value: 'effected'
  },
  {
    label: '停止',
    value: 'stopped'
  }
]

export const getStateLabel = (state: string) => stateOptions.find((it) => it.value === state)?.label ?? '未知'

const initPage: initPageType = {
  current: 1,
  total: 0,
  pageSize: 10,
  morePageOptions: true
}

const OrderList = () => {
  const [listType, setListType] = useState<'private' | 'team' | 'public'>('private')

  const [tableData, setTableData] = useState<any[]>([])

  const [inputValue, setInputValue] = useState('')
  const [status, setStatus] = useState('')

  const [allProjects, setAllProjects] = useState([])

  const [project, setProject] = useState<string | undefined>()

  const isMine = location.pathname.includes('myShoppingOrderList')

  const navigate = useNavigate()

  const permissions = getItem(PERMISSIONS)

  const columns = useMemo(
    () => [
      {
        title: '订单名称',
        key: 'name',
        dataIndex: 'name',
        render: (name: string, row: any) => (
          <Button
            type="link"
            onClick={() => {
              navigate(`/shoppingOrderDetail?id=${row.id}`)
            }}>
            {name}
          </Button>
        )
      },
      {
        title: '所属项目',
        key: 'proj_id',
        dataIndex: 'proj_id',
        render: (id) => allProjects.find((it) => it.value === id)?.label ?? '--'
      },
      {
        title: '提单人',
        key: 'owner',
        dataIndex: ['owner', 'name']
      },
      {
        title: '提单时间',
        key: 'created_at',
        dataIndex: 'created_at',
        render: (tiem) => hsHandleTableDateTime(tiem)
      },
      {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
        render: (state) => getStateLabel(state)
      },
      {
        title: '操作',
        key: 'operation',
        dataIndex: 'operation',
        render: (_, row) => (
          <>
            {row.status === 'stopped' ? (
              <Popconfirm
                title="确认删除？"
                onConfirm={() => {
                  deleteDraftOrder(row.id).then(() => {
                    message.success('删除成功')
                    resetPageAndTriggerRequest()
                  })
                }}>
                <Button type="link">删除</Button>
              </Popconfirm>
            ) : (
              <Popconfirm
                title="订单停止后，不可直接恢复。如需恢复，可复制订单内容到购物车，重新下单。"
                description="是否停止？"
                onConfirm={() => {
                  pauseTheOrder(row.id).then(() => {
                    message.success('停止成功')
                    handleChange(pagination.current)
                  })
                }}>
                <Button type="link">停止</Button>
              </Popconfirm>
            )}
            <Popconfirm
              title="该订单所有数据项，将被添加到购物车，并附带其所配置的内容"
              description="是否确定复制？"
              onConfirm={() => {
                copyOrdersToCart(row.id).then(() => {
                  message.success('复制成功')
                  navigate('/shoppingCart')
                })
              }}>
              <Button type="link">复制</Button>
            </Popconfirm>
          </>
        )
      }
    ],
    [allProjects, navigate]
  )

  const searchWord = useRef('')

  const getList = useCallback(
    async (page: number, pageSize: number) => {
      const res = await getOrderList({
        page: page,
        page_size: pageSize,
        compound_status: listType,
        draft: false,
        keywords: searchWord.current || undefined,
        status: status || undefined,
        proj_id: project ?? undefined
      })
      setTableData(res.items)
      return res.total
    },
    [listType, project, status]
  )

  const { pagination, resetPageAndTriggerRequest, handleChange } = usePageChange(initPage, getList)

  useEffect(() => {
    resetPageAndTriggerRequest()
  }, [resetPageAndTriggerRequest])

  useEffect(() => {
    clearLocalShopping()
    getAllProjectOptions().then((res) => {
      setAllProjects(res)
    })
  }, [])

  return (
    <div className="flex flex-col bg-white p4 gap-4">
      {!isMine && (
        <Radio.Group
          onChange={(e) => {
            setListType(e.target.value)
          }}
          value={listType}>
          <Radio value={'private'}>我提交的</Radio>
          {permissions?.includes('datashop.product_order.project.view') && <Radio value={'team'}>我的团队</Radio>}
          {permissions?.includes('datashop.product_order.all.view') && <Radio value={'public'}>全部</Radio>}
        </Radio.Group>
      )}
      <div className="grid grid-cols-7">
        <div className="col-span-6 grid grid-cols-[3fr_3fr_2fr] gap-6">
          <div className="flex gap-2">
            <Input
              {...commonInputProps()}
              value={inputValue}
              onChange={(e) => {
                setInputValue(e.target.value)
              }}
              placeholder="请输入订单、提单人名称"
            />
            <Button
              type="primary"
              onClick={() => {
                searchWord.current = inputValue
                resetPageAndTriggerRequest()
              }}>
              搜索
            </Button>
          </div>
          <div className="flex items-center">
            所属项目：
            <Select
              value={project}
              onChange={(value) => {
                setProject(value)
              }}
              {...commonSelectProps}
              options={allProjects}
              className="flex-1"
              allowClear
              showSearch
              filterOption={(input: string, option?: { label: string; value: string }) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
            />
          </div>
          <div className="flex items-center">
            状态：
            <Select
              {...commonSelectProps}
              value={status}
              onChange={(value) => {
                setStatus(value)
              }}
              className="flex-1"
              options={stateOptions}
            />
          </div>
        </div>
      </div>
      <Table
        columns={columns}
        dataSource={tableData}
        rowKey="id"
        pagination={{
          ...pagination,
          showTotal: (total) => `共 ${total} 条数据`
        }}
      />
    </div>
  )
}

export default OrderList
